import { Action, combineSlices, configureStore, ThunkAction } from '@reduxjs/toolkit';
import { persistReducer } from 'redux-persist'
import { loginSlice } from './features/login/loginSlice';
import sessionStorage from 'redux-persist/lib/storage/session';
import { shallowEqual } from 'react-redux';
import { flagSlice } from './features/flag/flagSlice';
import { persistStore } from 'redux-persist';
import { teamSlice } from './features/team/teamSlice';
import { reportSlice } from './features/report/reportSlice';
import { joinSlice } from './features/join/joinSlice';

const rootReducer = combineSlices(loginSlice, flagSlice, teamSlice, reportSlice, joinSlice)

const persistConfig = {
    key: 'root', // 自动框架生产的根目录id 是root。不变
    storage: sessionStorage, // 这个是选择用什么存储，session 还是 storage
}

// 一个经过处理的reducer
const persistedReducer = persistReducer(persistConfig, rootReducer)

export const makeStore = () => {
    return configureStore({
        reducer: persistedReducer,
        middleware: (getDefaultMiddleware) =>
            getDefaultMiddleware({
                serializableCheck: false,
            }),
    })
}
export const persistor = persistStore(makeStore())

export const resetState = async () => {
    await persistor.purge()
    persistor.flush()
    const newRootReducer = persistReducer(persistConfig, rootReducer)
    makeStore().replaceReducer(newRootReducer)
}


// 进行值得浅层对比。如果值一样，就不更新值
export const useAppShallowEqual = shallowEqual

export type AppStore = ReturnType<typeof makeStore>
export type RootState = ReturnType<typeof rootReducer>;
// Infer the `RootState` and `AppDispatch` types from the store itself
export type AppDispatch = AppStore['dispatch']
export type AppThunk<ThunkReturnType = void> = ThunkAction<
    ThunkReturnType,
    RootState,
    unknown,
    Action
>;
